//
//  TSCVCSelectShop.m
//  Tsc_IOS
//
//  Created by Rio on 15-6-2.
//  Copyright (c) 2015年 idream. All rights reserved.
//

#import "TSCVCSelectShop.h"
#import "TSCConstants.h"
#import "TSCMyUIUtil.h"
#import "TSCMyHttpUtil.h"
#import "TSCMyNetworkUtil.h"
#import "TSCJsonShop.h"
#import "TSCFragBtnGetMore.h"
#import "TSCFragBtnNotFound.h"
#import "TSCVCCreateShopGatherInfo.h"

@interface TSCVCSelectShop () {
    // 输入项
    NSString * _iShopName;
    NSInteger _iCityId;
    
    UITableView * _tvShop;
    TSCFragBtnGetMore * _fragBtnGetMore;
    TSCFragBtnNotFound * _fragBtnNotFound;
    NSMutableArray * _shopArray; // 保存server返回的shop数组
    
    BOOL _hasMoreData; // 是否还能从server获得更多数据
}

@end

@implementation TSCVCSelectShop

#pragma mark 校验并获取输入
- (void) getVCInput:(NSNotificationCenter *)notification {
    [super getVCInput:notification];
    
    _iShopName = [_inputDic objectForKey:AEKI_SHOP_NAME] ;
    _iCityId = [[_inputDic objectForKey:AEKI_CITY_ID] intValue];
    
    NSAssert(_iShopName != nil, @"%s: 输入参数必须包括：%@！", __FUNCTION__, AEKI_SHOP_NAME);
    NSAssert(_iCityId != 0, @"%s: 输入参数必须包括：%@！", __FUNCTION__, AEKI_CITY_ID);
}

+ (id) vcSelectShopWithStoryboard {
    UIStoryboard * sb = [UIStoryboard storyboardWithName:UI_STORYBOARD_NAME_MAIN bundle:[NSBundle mainBundle]];
    return [sb instantiateViewControllerWithIdentifier:UI_VC_NAME_SELECT_SHOP];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 设置自定义导航栏
    _nbc = [[TSCMyNaviBarCreator alloc]initAndCreateWithViewController:self hasGoBackButton:YES goBackVC:nil hasAppLogo:YES titleResourceKey:@"title_select_shop" iconResourceNameArray:nil iconClickedListenerArray:nil];
    
    // 初始化类属性
    _shopArray = [NSMutableArray array];
    _hasMoreData = NO;
    
    // ===== 初始化UI
    
    // 奇怪，突然又不需要了，加上反而使table下移了
    //    // 获得nvb的frame
    //    CGRect nvbRect = self.navigationController.navigationBar.frame;
    //    CGFloat tvX = 0;
    //    CGFloat tvY = nvbRect.origin.y + nvbRect.size.height;
    //    CGFloat tvW = UI_SCREEN_WIDTH;
    //    CGFloat tvH = UI_SCREEN_HEIGHT - tvY; // 占据屏幕除nvb之外的全部高度
    
    // 初始化tvShop
    _tvShop = [[UITableView alloc]init];
    _tvShop.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _tvShop.scrollEnabled = YES;
    _tvShop.backgroundColor = COLOR_TRANSPARENT;
    [self.view addSubview:_tvShop];
    
    // 设置tvShop的footerView
    _fragBtnGetMore = [[TSCFragBtnGetMore alloc]init];
    _fragBtnNotFound = [[TSCFragBtnNotFound alloc]init];
    
    UIView * footerView = [[UIView alloc]init];
    footerView.frame = CGRectMake(0, 0, 0, 100.0f); // 指定footerView的高度
    [footerView addSubview:_fragBtnGetMore];
    [footerView addSubview:_fragBtnNotFound];
    _tvShop.tableFooterView = footerView;
    
    // 添加约束
    // 添加table约束：填充全部父view
    _tvShop.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_tvShop]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tvShop)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_tvShop]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_tvShop)]];
    // 添加footerView约束
    _fragBtnGetMore.translatesAutoresizingMaskIntoConstraints = NO;
    _fragBtnNotFound.translatesAutoresizingMaskIntoConstraints = NO;
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_fragBtnGetMore]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_fragBtnGetMore)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-0-[_fragBtnNotFound]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_fragBtnNotFound)]];
    [NSLayoutConstraint activateConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-0-[_fragBtnGetMore(==50)]-0-[_fragBtnNotFound(==50)]-0-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(_fragBtnGetMore,_fragBtnNotFound)]];
    
    // ===== 注册事件
    // 注册事件——注册代理
    _tvShop.dataSource = self;
    _tvShop.delegate = self;
    
    // 注册事件——获得更多
    __weak typeof (self) _weakSelf = self;
    _fragBtnGetMore.btnClickListener = ^(UIButton * btn) {
        typeof (self) _strongSelf = _weakSelf;
        
        if (_strongSelf) {
            [_strongSelf searchShop_PP1:NO cityId:_strongSelf->_iCityId shopName:_strongSelf->_iShopName];
        } else {
            NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
        }
    };
    
    // 注册事件——找不到
    _fragBtnNotFound.btnClickListener = ^(UIButton * btn) {
        typeof (self) _strongSelf = _weakSelf;
        
        if (_strongSelf) {
            // 退出当前vc
            UINavigationController * nvc = [_strongSelf navigationController];
            [nvc popViewControllerAnimated:NO];
            
            // 进入创建店铺vc
            TSCVCCreateShopGatherInfo * vcCreateShop = [TSCVCCreateShopGatherInfo vcCreateShopWithStoryboard];
            [nvc pushViewController:vcCreateShop animated:YES];
            
            // VC间传递参数
            NSDictionary * inputDic = [NSDictionary dictionaryWithObject:[NSNumber numberWithLong:_strongSelf->_iCityId ] forKey:AEKI_CITY_ID];
            [[NSNotificationCenter defaultCenter]addObserver:vcCreateShop selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_CREATE_SHOP_GATHER_INFO object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_CREATE_SHOP_GATHER_INFO object:inputDic];
        } else {
            NSLog(@"[W]%s: block中的弱引用为nil，导致block内部代码无法正常执行！", __FUNCTION__);
        }
    };
    
    // 向Server查询店铺
    [self searchShop_PP1:YES cityId:_iCityId shopName:_iShopName];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

#pragma mark 私有方法
/* private */ - (void) searchShop_PP1:(BOOL)isShowQueryDialog cityId:(NSInteger)cityId shopName:(NSString *)shopName {
    
    // 先检查网络情况，若不可用，直接返回
    if ([TSCMyNetworkUtil checkNetwork] == false) {
        [TSCMyUIUtil popErrWithResourceKey:@"err_network_unavailable"];
        return;
    }
    
    // 显示查询提示
    [self setBtnGetMoreDisSearching];
    if (isShowQueryDialog == true) {
        [self showDialogWithResourceKey:@"content_searching" isProcessing:YES];
    }
    
    // 拼装请求
    NSMutableDictionary * reqDic = [[NSMutableDictionary alloc] init];
    [reqDic setObject:[_ud objectForKey:UD_USER_ID] forKey:@"user_id"];
    [reqDic setObject:[_ud objectForKey:UD_LOGIN_KEY] forKey:@"login_key"];
    [reqDic setObject:[NSNumber numberWithLong:URL_MATCH_TYPE_ANY] forKey:@"match_type"];
    [reqDic setObject:[NSNumber numberWithLong:cityId] forKey:@"city_id"];
    [reqDic setObject:shopName forKey:@"name"];
    [reqDic setObject:[NSNumber numberWithLong:[_shopArray count]] forKey:@"offset"];
    
    // 发送请求
    [TSCMyHttpUtil postWithUrl:URL_SEARCH_SHOP dictionary:reqDic completionHandler:^(ServerRespType serverRespType, NSString * respString, NSDictionary *respDictionary, NSInteger code, NSString *msg, NSDictionary *contentDictionary) {
        // 服务器返回错误处理
        switch (serverRespType) {
            case ServerRespTypeSuccess:
                break;
            case ServerRespTypeErrNil:
            case ServerRespTypeErrJson: {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self dissmisDialog];
                    [TSCMyUIUtil popErrWithResourceKey:@"err_web_server_unavailable"];
                });
                return;
            }
            case ServerRespTypeErrCode:{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self dissmisDialog];
                    [TSCMyUIUtil popErrWithString:msg];
                });
                return;
            }
            default:
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self dissmisDialog];
                    [TSCMyUIUtil popErrWithResourceKey:@"err_system"];
                });
                return;
        }
        
        // 解析服务器返回
        NSArray * shopArray = (NSArray *) contentDictionary; // 注：此时content是Array
        NSMutableArray * shopJsonArray = [NSMutableArray array];
        for (NSDictionary * shopDic in shopArray) {
            TSCJsonShop * shopJson = [[TSCJsonShop alloc]init];
            shopJson.Id = [[shopDic objectForKey:@"id"] intValue];
            shopJson.name = [shopDic objectForKey:@"name"];
            [shopJsonArray addObject:shopJson];
        }
        
        // 回到主线程继续...
        [self performSelectorOnMainThread:@selector(searchShop_PP2:) withObject:shopJsonArray waitUntilDone:YES];
        
    }];
}

/* private */ - (void) searchShop_PP2:(NSArray *)shopJsonArray {
    // 有返回待显示的数据
    if ([shopJsonArray count] != 0) {
        // 更新显示数据
        [_shopArray addObjectsFromArray:shopJsonArray];
        [_tvShop reloadData];
        
        // 更新“更多”按钮显示
        [self setBtnGetMoreDisHasData];
        
        // 更新标识位
        _hasMoreData = YES;
    }
    // 某次查询未返回任何数据
    else {
        // “更多”按钮不可用
        [self setBtnGetMoreDisNoData];
        
        // 更新标识位
        _hasMoreData = NO;
    }
    
    // 查询完毕后关闭提示框
    [self dissmisDialog];
}

/* private */ - (void) setBtnGetMoreDisSearching {
    [_fragBtnGetMore setBtnEnabled:NO];
    [_fragBtnGetMore setBtnTitle:NSLocalizedString(@"btn_searching", nil) forState:UIControlStateDisabled];
}

/* private */ - (void) setBtnGetMoreDisHasData {
    [_fragBtnGetMore setBtnEnabled:YES];
    [_fragBtnGetMore setBtnTitle:NSLocalizedString(@"btn_get_more", nil) forState:UIControlStateNormal];
}

/* private */ - (void) setBtnGetMoreDisNoData {
    [_fragBtnGetMore setBtnEnabled:NO];
    [_fragBtnGetMore setBtnTitle:NSLocalizedString(@"btn_no_more", nil) forState:UIControlStateDisabled];
}

#pragma mark UITableView及其代理的生命周期方法

// 获得总行数
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [_shopArray count];
}

// 每一行内容是什么
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellReuseId = @"textCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseId];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellReuseId];
        cell.backgroundColor = COLOR_MT_SPINNER_CELL_BG;
    }
    
    TSCJsonShop * shopJson = [_shopArray objectAtIndex:indexPath.row];
    NSString * text;
    if ([shopJson isKindOfClass:[TSCJsonShop class]] == NO) {
        NSLog(@"[W]%s: TableView数据源中，存在不是TSCJsonShop类型的数据！显示时将抛出异常！数据源中的对象：%@", __FUNCTION__, text);
        
        // 设置为错误提示
        text = @"数据源类型不是NSString！";
    } else {
        text = shopJson.name;
    }
    
    cell.textLabel.text = text;
    return cell;
}

// 注册事件——选择某行后
- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 找到倒数第3个vc（应该是Reg2GatherInfoGuide）
    NSArray * vcArray = [self navigationController].viewControllers;
    UIViewController * lastVC = [vcArray objectAtIndex:([vcArray count] - 3)];
    [[self navigationController]popToViewController:lastVC animated:YES];
    
    // VC间传递参数
    TSCJsonShop * selectedShopJson = [_shopArray objectAtIndex:indexPath.row];
    NSDictionary * inputDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSNumber numberWithLong:selectedShopJson.Id], selectedShopJson.name, nil] forKeys:[NSArray arrayWithObjects:AEKI_SHOP_ID, AEKI_SHOP_NAME, nil]];
    [[NSNotificationCenter defaultCenter]addObserver:lastVC selector:@selector(SELECTOR_GET_VC_INPUT) name:UI_VC_NAME_REG2_GATHER_INFO_GUIDE object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:UI_VC_NAME_REG2_GATHER_INFO_GUIDE object:inputDic];
    
}

// 注册事件——自动获得更多
- (void) tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    // 如果将要显示最后一行，并且后续server还可能返回数据
    if (indexPath.row == ([_shopArray count] - 1) && _hasMoreData == YES) {
        [self searchShop_PP1:NO cityId:_iCityId shopName:_iShopName];
    }
}

//- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
//    return 100.0f;
//}


@end
